<?php
// 设置允许的来源，这里假设允许来自 http://localhost:9528 的请求
header("Access-Control-Allow-Origin: http://localhost:9528");
// 允许携带凭证
header("Access-Control-Allow-Credentials: true");
// 允许的HTTP方法
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// 允许的请求头
header("Access-Control-Allow-Headers: Content-Type");

// 处理预检请求（OPTIONS）
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 连接数据库
require_once "./conn.php";
require_once "./usersession.php";

if ($conn->connect_error) {
    die(json_encode(["Code" => 500, 'Ret' => "False", "Data" => "", "Msg" => "" . $conn->connect_error]));
}
// 获取前端传递的 JSON 数据
$data = json_decode(file_get_contents("php://input"), true);
// 获取配置ID
$configId = isset($data['id']) ? intval($data['id']) : 0;

if ($configId <= 0) {
    die(json_encode(["Code" => 400, 'Ret' => "False", "Data" => "", "Msg" => "请传配置ID"]));
}

// 查询配置详情
$sql = "SELECT * FROM configurations WHERE id = $configId AND zhongkong_name = '$username'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    // 假设字段内容是 JSON 字符串，先解码为数组
    foreach ($row as $key => $value) {
        if (is_string($value) && is_json($value)) {
            $row[$key] = json_decode($value, true);
        }
    }
    echo json_encode([
        "Code" => 200,
        "Data" => $row,
        "Msg" => "查询成功",
        "Ret" => "True"
    ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode([
        "Code" => 404,
        "Data" => "",
        "Msg" => "配置未找到",
        "Ret" => "False"
    ]);
}

$conn->close();

// 辅助函数：判断字符串是否为合法 JSON
function is_json($string)
{
    json_decode($string);
    return json_last_error() === JSON_ERROR_NONE;
}